import axios from 'axios'
import { Toast } from 'mint-ui'
import qs from 'querystring'
import EventEmitter from 'events'
import mt from 'moment'
import 'moment/locale/zh-cn'
import {STORAGE_TYPE} from './config'
import store from '../../store'
import nodeUrl from 'url'

mt.locale('zh-cn')

export const moment = mt

const defaultAxiosConf = {
  timeout: GLOBAL_CONF.XHR_TIMEOUT,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  },
  baseURL: GLOBAL_CONF.BASE_URL
}

export function http(params = {}, fn) {
  mergeData(params.data)
  if (typeof fn === 'function') fn(true)
  if (params.data && !(params.data instanceof FormData)) params.data = qs.stringify(params.data)
  if (!params.method) params.method = 'get'
  if (params.method.toLowerCase() === 'get') params.url += `?${qs.stringify(params.data)}`
  return axios({...defaultAxiosConf, ...params}).then(res => {
    if (typeof fn === 'function') fn(false)
    if (res.data.result === 0) throw new Error(res.data.message)
    return res.data
  }).catch(err => {
    if (typeof fn === 'function') fn(false)
    const {tip = true} = params
    let message
    if (err.message && !/Request failed|timeout/i.test(err.message)) {
      message = err.message
    } else {
      message = '目前访问人数过多，请稍后再试~'
    }
    if (tip) Toast(message)
    throw err
  })
}

export function upload(url, form, params, fn, cb) {
  if (params) {
    mergeData(params)
    url = `${url}?${qs.stringify(params)}`
  }
  return http({
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    url: url,
    data: form,
    onUploadProgress(processEvent) {
      // 原生进度事件
      const percent = processEvent.loaded / processEvent.total * 100
      cb(percent)
    }
  }, fn)
}

// 网络请求前加工数据
export function mergeData(data) {
  if (data && !(data instanceof FormData)) {
    // 每次网络请求前需要传递用户登录token或设备accessToken，优先传递token
    const accessToken = localStorage.getItem(STORAGE_TYPE.deviceToken)
    const token = store.state.userInfo ? store.state.userInfo.token : ''
    const deviceId = localStorage.getItem(STORAGE_TYPE.deviceId) || ''
    let tokenName
    let tokenValue
    if (token) {
      tokenName = 'token'
      tokenValue = token
    } else {
      tokenName = 'accessToken'
      tokenValue = accessToken
    }
    data[tokenName] = tokenValue
    data.device = deviceId
  }
}

// 表单值回显
export function echo(target, resource) {
  for (let i in target) {
    if (target.hasOwnProperty(i)) {
      if (resource && resource[i] !== null && typeof resource[i] !== 'undefined') {
        target[i] = resource[i]
      }
    }
  }
}

// 表单验证
export function validate(form) {
  return new Promise((resolve, reject) => {
    for (let i in form) {
      if (form.hasOwnProperty(i)) {
        if (this.$refs[i]) {
          let validValue = this.$refs[i].validValue()
          if (validValue instanceof Error) {
            return reject(validValue)
          }
        }
      }
    }
    return resolve()
  })
}

class MyEvent extends EventEmitter {}

export const eventEmitter = new MyEvent()

export function parse(str) {
  if (!str) return null
  let json
  try {
    json = JSON.parse(str)
  } catch (err) {
    json = null
  }
  return json
}

// 删除对象中值为null的键
export function delNull(data) {
  for (let i in data) {
    if (data.hasOwnProperty(i) && data[i] === null) {
      delete data[i]
    }
  }
}

export function debounce(func, delay = 300) {
  let timer
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func(...args)
    }, delay)
  }
}

// 数组转表单
export function arrToForm(arr, name) {
  const map = {}
  arr.forEach((item, index) => {
    for (let i in item) {
      if (item.hasOwnProperty(i)) {
        map[`${name}[${index}].${i}`] = item[i]
      }
    }
  })
  return map
}

// 个人档案信息查询
export function personalRecord(cb) {
  return http({
    method: 'post',
    url: '/admin/person/sapi/person/center/my/archive/get',
    data: {},
    tip: false
  }, cb).then(res => {
    return Promise.resolve(res.data)
  }).catch(err => {
    return Promise.reject(err)
  })
}

// 解析query
export function queryParse (str) {
  if (typeof str === 'undefined') str = window.location.href
  if (typeof str !== 'string') return {}
  const search = nodeUrl.parse(str).search
  if (search) {
    return qs.parse(search.substr(1))
  } else {
    return {}
  }
}

// 是否为微信环境
export function isWeChat() {
  return /MicroMessenger/i.test(navigator.userAgent) && !/miniprogram/i.test(navigator.userAgent)
}

export function isMp() {
  return /miniprogram/i.test(navigator.userAgent)
}

// 下载文件
export function download(url) {
  let a = document.createElement('a')
  const filePath = nodeUrl.parse(url).pathname
  a.download = filePath.substring(filePath.lastIndexOf('/') + 1, filePath.lastIndexOf('.'))
  a.href = url
  a.target = '_blank'
  a.type = 'application/octet-stream'
  a.click()
}
